package x.y.z;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

public class Interview_4_3_ListOfDepths {
    public ListNode[] listOfDepth(TreeNode tree) {
        if (tree == null) {
            return new ListNode[0];
        }
        ArrayList<ListNode> listResult = new ArrayList<>();
        ListNode dummy = new ListNode(0);
        ListNode cur = dummy;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(tree);
        while (!queue.isEmpty()) {
            int size = queue.size();
            while (size > 0) {
                TreeNode treeNode = queue.poll();
                if (treeNode.left != null) {
                    queue.offer(treeNode.left);
                }
                if (treeNode.right != null) {
                    queue.offer(treeNode.right);
                }
                ListNode listNode = new ListNode(treeNode.val);
                cur.next = listNode;
                cur = listNode;
                size--;
            }
            listResult.add(dummy.next);
            dummy = new ListNode(0);
            cur = dummy;
        }
        ListNode[] result = new ListNode[listResult.size()];
        for (int i = 0; i < listResult.size(); i++) {
            result[i] = listResult.get(i);
        }
        return result;
    }
}
